package class02;

//环状数组
public class Code04_RingArray {

    public static class MyQueue {
        private int[] arr;
        //压入指针
        private int pushi;
        //弹出指针
        private int polli;
        //队列大小, 通过size来解耦pushi与polli的追赶关系(追赶关系处理比较复杂)
        private int size;
        //队列大小上限
        private final int limit;

        public MyQueue(int limit) {
            arr = new int[limit];
            pushi = 0;
            polli = 0;
            size = 0;
            this.limit = limit;
        }

        public void push(int value) {
            if (size == limit) {
                throw new RuntimeException("栈满了，不能再加了");
            }
            //现有数量大小+1
            size++;
            //赋值
            arr[pushi] = value;
            //获取下一次压入地址
            pushi = nextIndex(pushi);
        }

        public int pop() {
            if (size == 0) {
                throw new RuntimeException("栈空了，不能再拿了");
            }
            size--;
            int ans = arr[polli];
            polli = nextIndex(polli);
            return ans;
        }

        public boolean isEmpty() {
            return size == 0;
        }

        // 如果现在的下标是i，返回下一个位置
        private int nextIndex(int i) {
            //判断是否达到最大下标位置
            return i < limit - 1 ? i + 1 : 0;
        }

    }

}
